package com.syblood.app.utils;

import android.media.MediaScannerConnection;
import android.net.Uri;
import android.text.TextUtils;

import com.syblood.app.application.AppContext;
import com.syblood.app.constants.Constants;

/**
 * @CreateTime : 2022/11/6 14:08
 * @Author : JiChangkong
 * @Description :
 */
public class MediaScanner {
    private MediaScannerConnection mediaScannerConnection = null;
    private PhotoScannerClient client = null;
    private String filePath = null;
    private String fileType = null;
    private boolean isVideoType = false;

    private MediaScanner() {
        if (client == null) {
            client = new PhotoScannerClient();
        }

        if (mediaScannerConnection == null) {
            mediaScannerConnection = new MediaScannerConnection(AppContext.context(), client);
        }
    }

    private static class Builder {
        private static final MediaScanner INSTANCE = new MediaScanner();
    }

    public static MediaScanner getInstance() {
        return Builder.INSTANCE;
    }

    /**
     * @param path
     * @param type eg: audio/mp3 media/* application/ogg 图片：image/jpeg 视频：video/mp4
     */
    public void scanFile(String path, String type) {
        LogUtil.d("scanFile, path : " + path);
        this.filePath = path;
        this.fileType = type;
        isVideoType = !TextUtils.isEmpty(type) && Constants.MEDIA_TYPE_VIDEO.equalsIgnoreCase(type);
        mediaScannerConnection.connect();
    }

    private class PhotoScannerClient implements MediaScannerConnection.MediaScannerConnectionClient {

        @Override
        public void onMediaScannerConnected() {
            if (filePath != null) {
                mediaScannerConnection.scanFile(filePath, fileType);
            }
            filePath = null;
            fileType = null;
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            LogUtil.d("path : " + path + " and uri : " + uri);

            mediaScannerConnection.disconnect();
            isVideoType = false;

        }
    }
}
